package com.szsfm.vehiclemanagement.util;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

/**
 * Created by zhoubigbo on 2017/11/27.
 */
public class ToastUtil {

    private static Context mAppContext;
    private static Toast mToast = null;
    private static Looper mainLooper = Looper.getMainLooper();
    private static CharSequence mText;

    public static void setContext(Application app) {
        mAppContext = app.getApplicationContext();
    }

    public static void show(final CharSequence text) {
        if (mAppContext==null){
            throw new NullPointerException("请在application调用setContext");
        }
        destroyToast();
        mText = text;
        if (mainLooper != Looper.myLooper()) {//如果不是在主线程
            handler.post(runnable);
        } else {
            createToast();
        }
    }

    private static Handler handler = new Handler(mainLooper);

    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            createToast();
        }
    };

    private static void destroyToast() {
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = null;
    }

    private static void createToast() {
        mToast = Toast.makeText(mAppContext, mText, Toast.LENGTH_LONG);
        mToast.show();
    }

}
